<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace frontend\v1;

use Yii;
use yii\rest\Controller;
use yii\filters\VerbFilter;
use yii\filters\RateLimiter;
use builder\base\Http;
use frontend\v1\behaviors\CompositeAuthX;
use frontend\v1\behaviors\QueryParamAuthX;
use frontend\v1\behaviors\HttpHeaderAuthX;

/**
 * 接口继承类
 * @property-read \common\models\User|null $user an instance of The user model
 * @property-read \yii\caching\CacheInterface|null $cache an instance of The cache driver
 * @property-read \yii\db\Connection $db an instance of The db connection
 * @author cleverstone
 * @since ym2.0
 */
abstract class RestController extends Controller
{
    use Http;

    /**
     * 请求动作定义
     * @var array Verbs to specify the actions.
     */
    public $actionVerbs = [];

    /**
     * 游客可以访问的action-id。
     * @var array Define actions that don't require authorization.
     */
    public $guestActions = [];

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        // 直接覆盖父级行为定义, 便于更改
        return [
            'verbFilter' => [
                'class' => VerbFilter::class,
                'actions' => $this->actionVerbs,
            ],
            // This is a composite auth with query param.
            /*'authenticator' => [
                'class' => CompositeAuthX::class,
                'user' => Yii::$app->user,
                'optional' => $this->guestActions,
                'authMethods' => [
                    'queryParamAuth' => [
                        'class' => QueryParamAuthX::class,
                        'tokenParam' => '_access_token',
                    ],
                ],
            ],*/
            // This is a basic auth with X-Api-Key in request header.
            'headerAuth' => [
                'class' => HttpHeaderAuthX::class,
                'user' => Yii::$app->user,
                'optional' => $this->guestActions,
                'header' => 'X-Api-Key',
                'pattern' => '/^Auth:(.*?)$/',
            ],
            // 如需开启, 则需要User模型实现 \yii\filters\RateLimitInterface
            /*'rateLimiter' => [
                'class' => RateLimiter::class,
            ],*/
        ];
    }

    /**
     * @return \common\models\User|null
     */
    public function getUser()
    {
        return Yii::$app->getUser()->getIdentity();
    }

    /**
     * @return \yii\caching\CacheInterface|null
     */
    public function getCache()
    {
        return Yii::$app->getCache();
    }

    /**
     * @return \yii\db\Connection
     */
    public function getDb()
    {
        return Yii::$app->getDb();
    }
}